import {
    getCourseInfo,
    getCourseCatalog,
    getCourseIntro
} from '../../data-model/model-courese';
import { navigateTo } from '../../common/service/page-service';
import { showAlertModel } from '../../common/service/alter-service';
import {
    setCurrentPlayList,
    getCurrentAudioLesson,
    getStudiedLesson
} from '../../common/service/courses-service';
import {
    getLoginStatus,
    getUserInfo
} from '../../common/service/user-service';
import {
    LOGIN_STATUS,
    EVENT_BUS_KEY,
    PAY_ERROR
} from '../../common/constants';
import { eventBusGetter } from '../../utils/eventbus';
import { payment } from '../../common/service/payment-service';
import {
    showLoading,
    hideLoading
} from '../../common/service/toast-service';

Page({
    data: {
        curPanelId: 1,
        list: [
            {
                tagId: 1,
                tagName: '详情'
            },
            {
                tagId: 2,
                tagName: '目录'
            }
        ],
        refreshStatus: 0,
        courseInfo: null,
        courseIntro: null,
        courseCatalog: null,
        coursePlayList: null,
        promiseForCourseCataLog: null,
        subscribeTimeLimit: null,
        isPlaying: false
    },
    onLoad: function (options) {
        console.log('index onLoad');
        // 当调用正和岛登录流程后，无论登录成功或失败，都初始化详情页面数据
        let initAfterLogin = () => {
            let loginStatus = getLoginStatus();
            if ([
                LOGIN_STATUS.ZH_LOGIN_SUCCESS,
                LOGIN_STATUS.ZH_LOGIN_FAILED
            ].indexOf(loginStatus) > -1) {
                this._initPageDatas(options);
                // 获取课程介绍
                let {courseId} = options;
                this._getCourseIntro(courseId);
            }
        };
        initAfterLogin();
        eventBusGetter().$on(EVENT_BUS_KEY.LOGIN_STATUS_UPDATE, () => {
            initAfterLogin();
        });
        eventBusGetter().$on([
            EVENT_BUS_KEY.PLAYER_STAT_STOPPED,
            EVENT_BUS_KEY.PLAYER_STAT_RESUMED,
            EVENT_BUS_KEY.PLAYER_STAT_PAUSED
        ], () => {
            this._setLessonListStatus();
        });
    },
    onShow: function (e) {
        console.log('index onShow');
        var promise = this.data.promiseForCourseCataLog;
        promise && promise.then(res => {
            this._setLessonListStatus();
        });
        this.setData({
            refreshStatus: new Date().getTime()
        });
    },
    onShareAppMessage () {
        var shareInfo = this.data.courseInfo.shareInfo;
        return {
            title: shareInfo.title,
            path: shareInfo.miniProgramPath,
            imageUrl: shareInfo.img
        };
    },
    onTrialBtnTapped (evt) {
        var firstOfPlayList = this.data.playList[0];
        navigateTo({
            url: `/pages/listen/listen?courseId=${this.data.courseInfo.courseId}&lessonId=${firstOfPlayList.lessonId}`
        });
    },
    // 课节列表项目被点击
    onLessonItemTap (evt) {
        if ((evt.detail.showTrial === 1 || this.data.courseInfo.purchaseStatus > 1) && evt.detail.lessonStatus !== 3) {
            navigateTo({
                url: `/pages/listen/listen?courseId=${this.data.courseInfo.courseId}&lessonId=${evt.detail.lessonId}`
            });
        } else if (evt.detail.showTrial !== 1 && this.data.courseInfo.purchaseStatus === 1 && this.data.courseInfo.lessonStatus !== 3) {
            let tipMap = {
                course: `本课程共${this.data.lessonsCount}课时，购买后即可学习`,
                sub: `本专栏已更新${this.data.lessonsCount}篇文章，购买后即可学习`
            };
            showAlertModel({
                content: this.data.courseInfo.type === 1 ? tipMap.course : tipMap.sub,
                cancelText: '再想想',
                confirmText: '立即购买'
            }).then((res) => {
                if (res.confirm === true) {
                    this._doPayment();
                }
            });
        }
    },
    onTabSelected (evt) {
        this.setData({
            curPanelId: evt.detail.tagId
        });
    },
    onFooterBtnTap () {
        this._doPayment();
    },
    _setLessonListStatus () {
        let lessonInfo = getCurrentAudioLesson();
        this.setData({
            isPlaying: !!lessonInfo
        });
        let lessonId = lessonInfo ? lessonInfo.lessonId : null;
        this._toggleLessonBoolProp(lessonId, 'isPlaying');
        let latestStudiedLesson = getStudiedLesson()[0];
        if (latestStudiedLesson) {
            this._toggleLessonBoolProp(latestStudiedLesson.lessonId, 'isLatestPlayed');
        }
    },
    _doPayment () {
        let checkPaymentResult = () => {
            this._initPageDatas({
                courseId: this.data.courseInfo.courseId
            }).then(res => {
                if (this.data.courseInfo.purchaseStatus > 1) {
                    // 发送购买成功通知
                    eventBusGetter().$emit(EVENT_BUS_KEY.PAY_COURSE_SUCCESS, this.data.courseInfo.courseId);
                    showAlertModel({
                        content: `本${this.data.courseInfo.type === 1 ? '课程' : '专栏'}已经加入你的已购列表中，现在即可学习`,
                        showCancel: false,
                        confirmText: '我知道了'
                    });
                } else {
                    showAlertModel({
                        title: '暂未获得支付结果',
                        content: '如您支付失败但仍有扣款，请联系正和岛客服电话400-100-9737',
                        cancelText: '关闭',
                        confirmText: '刷新',
                        success: (res) => {
                            if (res.confirm) {
                                checkPaymentResult();
                            }
                        }
                    });
                }
            });
        };
        if (getLoginStatus() === LOGIN_STATUS.ZH_LOGIN_SUCCESS) {
            payment(this.data.courseInfo.courseId).then(res => {
                checkPaymentResult();
            }, err => {
                if (err.errorCode === PAY_ERROR.REPEAT_PURCHASES) {
                    checkPaymentResult();
                }
            });
        } else {
            navigateTo({url: '/pages/login/login'});
        }
    },
    _getCourseIntro (courseId) {
        getCourseIntro(courseId).then(res => {
            this.setData({
                courseIntro: res
            });
        }, err => {
            console.log(err);
        });
    },
    // 初始化页面数据
    _initPageDatas (options) {
        // 从 页面url参数中获取:课程id
        showLoading();
        var {courseId} = options;
        if (getLoginStatus() === LOGIN_STATUS.ZH_LOGIN_SUCCESS) {
            var userInfo = getUserInfo();
            this.setData({
                userInfo: userInfo
            });
        }
        let cataLogPromise = getCourseInfo(courseId).then(res => {
            this.setData({
                courseInfo: res
            });
            let tmpPromise = getCourseCatalog(courseId);
            this.data.promiseForCourseCataLog = tmpPromise;
            return tmpPromise;
        }, err => {
            console.log(err);
        });
        cataLogPromise.then(res => {
            res.lessons.forEach((ele, index) => {
                ele.lessonNum = index + 1;
            });
            var allItems = [].concat(res.audioIntro, res.lessons);
            let playList = allItems.filter((ele) => {
                return ele.lessonStatus !== 3 && (ele.showTrial === 1 || this.data.courseInfo.purchaseStatus > 1);
            });
            let panelId = this.data.courseInfo.purchaseStatus === 1 ? 1 : 2;
            this.setData({
                curPanelId: panelId,
                courseCatalog: allItems,
                lessonsCount: res.lessons.length,
                subscribeTimeLimit: res.durationDesc ? res.durationDesc : '',
                playList: playList
            });
            setCurrentPlayList(JSON.parse(JSON.stringify(playList))).then((res) => {
                console.log(res);
            }, err => {
                console.log(err);
            });
            this._setLessonListStatus();
        }).catch(e => {
        }).then(res => {
            hideLoading();
        });
        return cataLogPromise;
    },
    // 高亮正在播放的条目
    _toggleLessonBoolProp (lessonId, propName) {
        if (this.data.courseCatalog == null) {
            return;
        }
        this.data.courseCatalog.forEach((ele) => {
            ele[propName] = ele.lessonId === lessonId;
        });
        this.setData({
            courseCatalog: this.data.courseCatalog
        });
    }
});
